#!/usr/bin/python
# -*- coding: UTF-8 -*-
#运行文件 人工智能.py
#作者 幽灵代码
#QQ 29672366
#邮箱 29672366@qq.com
#日期 2020.10.4

from xml.dom.minidom import parse
import xml.dom.minidom

import sys
import os

rootpath = os.getcwd()
corename = 'core'
libname = 'lib'
loaded = []
g = {}
theme = ''
import sqlite3 as db
import modelparse

exec('import ui as ui',g,g)

#加载数据库
cx=db.connect(rootpath+"/db/data.db",check_same_thread = False)
cu=cx.cursor()

def nlpexec(text,gui = False,lasttheme = False):
    global theme
    #首先获取相应的类，调用
    sql = "select question,classname,modulename from requestmap where '"+text+"' like '%'||question||'%' order by length(question) desc"
    if lasttheme:
        sql = "select question,classname,modulename from requestmap where modulename='"+ theme +"' and '"+text+"' like '%'||question||'%' order by length(question) desc"
    cu.execute(sql)
    nlp = ""
    for exp in cu.fetchall():
        if exp[2] not in loaded:
            domtree = xml.dom.minidom.parse(corename+'/'+exp[2]+".xml")
            modelparse.modelToExecute(domtree,g)
            loaded.append(exp[2])
        nlp = eval(exp[2]+'_'+exp[1],g,g)(text,exp[0],gui)
        theme = exp[2]
        return nlp
    theme = ""
    return nlp

def chatToBot(text,gui = False):
    global theme
    nlp = ""
    if theme!='':
        nlp = nlpexec(text,gui,True)
        if nlp != "":
            return nlp
    return nlpexec(text,gui)


